import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/ai/ai_item_entity.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import '../../../controller/pick/ai_model_logic.dart';
import '../../../entity/ai/ai_pay_entity.dart';
import '../../../resources/colours.dart';
import '../../../resources/styles.dart';
import '../../../utils/routes.dart';
import '../../../utils/user.dart';
import '../../../utils/utils.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../ai/ai_type.dart';

class AiPlanItem extends StatelessWidget {
  final CardStyle? cardStyle;
  final AiItemEntity item;
  final String? ticketName;
  final EdgeInsets? margin;
  final ValueChanged<bool>? onChange;
  final Function()? onTap;

  AiPlanItem(
      {super.key,
        this.cardStyle,
        required this.item,
        this.onChange,
        this.margin,
        this.onTap,
        this.ticketName
      });

  late final AiModelLogic logic = Get.find<AiModelLogic>(tag: AiType.plan.tag);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Block(
            cardStyle: cardStyle ??
                CardStyle(
                    margin: margin ?? const EdgeInsets.only(bottom: 8),
                    padding: const EdgeInsets.fromLTRB(12, 12, 12, 0)),
            child: Column(
              children: [
                top(),
                Container(height: 16),
                middle(),
                Container(height: 16),
                if(item.isOpen != 1 && item.content.noValue)...[
                  const Divider(height: 0.5,color: Colours.greyEE).paddingSymmetric(horizontal: 12),
                  bottom()
                ]else...[
                  planCount(item)
                ]
              ],
            )
        )
      ],
    );
  }

  Widget top() {
    return DefaultTextStyle(
      style: const TextStyle(color: Colours.grey66, fontSize: 11),
      child: GestureDetector(
        onTap: () => Get.toNamed(Routes.leagueDetail,arguments: "${item.leagueId}"),
        child: Row(
          children: [
            QkdText(item.leagueName ?? "",needCenter: true),
            Container(width: 6),
            QkdText(
              DateTime.tryParse(item.matchTime ?? "")
                ?.formatedString("MM-dd HH:mm"),
              height: 1.2,
            ),
            Container(width: 6),
            QkdText(ticketName ?? (item.matchNo ?? "")),
            const Spacer(),
            if(item.planTotal.hasValue)...[
              QkdText("${item.planTotal ?? 0}",
                height: 1.2,
                color: Colours.main
              ),
              QkdText("位专家已做出预测")
            ]
          ],
        ),
      ),
    );
  }

  Widget middle(){
    return GestureDetector(
      onTap: () => Get.toNamed(Routes.zqMatchDetail,arguments: item.matchId),
      child: Row(
        children: [
          Expanded(
              flex: 3,
              child: teamInfo(item.homeLogo, item.homeName, item.homeRanking, false)),
          Expanded(
              flex: 1,
              child: score(item.homeScore90, item.guestScore90).center),
          Expanded(
              flex: 3,
              child: teamInfo(item.guestLogo, item.guestName, item.guestRanking, true))
        ],
      ),
    );
  }

  Widget teamInfo(String? logo, String? name, String? rank, bool reverse){
    List<Widget> info = [
      CachedNetworkImage(
        width: 28,
        height: 28,
        placeholder: (context, url) => Styles.placeholderIcon(),
        errorWidget: (context, url, error,) =>
            Image.asset(Utils.getImgPath("zq_placeholder.png")),
        imageUrl: logo ?? ""
      ),
      Container(width: 8),
      Flexible(
        child: QkdText(name ?? "", fontWeight: FontWeight.w500),
      ),
      Container(width: 2),
      if (rank.hasValue)
        QkdText("[$rank]",fontSize: 11, color: Colours.grey99)
    ];
    return Row(
      mainAxisAlignment: reverse?MainAxisAlignment.end:MainAxisAlignment.start,
      children: reverse?info.reversed.toList():info
    );
  }

  Widget score(int? home,int? guest){
    return DefaultTextStyle(
      style: const TextStyle(
          fontSize: 14,fontWeight: FontWeight.w500,color: Colours.grey66),
      child: home != null && guest != null?
      QkdText("$home : $guest"):QkdText("vs"),
    );
  }



  Widget bottom() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(width: 16,Utils.getImgPath("ai_lock.png")),
          Container(width: 4),
          QkdText(item.priceId.hasValue?"${item.price?.changeUnit.trim()}解锁":"立即开通",color: Colours.main),
        ],
      ).tap(() async{
        onTap?.call();
        await User.needLogin(() async {
          if(item.priceId.hasValue){
            await logic.toPay(
                AiPrice(
                    id: item.priceId,
                    price: item.price == "会员免费"?"0":item.price,
                    aiId: item.aiMatchId
                )
            );
          }else {
            Get.toNamed(
                Routes.aiPay,arguments: AiType.plan.tag
            )?.then((value) => onChange?.call(true));
          }
        });
      })
    );
  }

  static Widget planCount(AiItemEntity? item){
    PlanCount? spf = item?.planCounts?.firstWhereOrNull((element) => element.playType == 1001);
    PlanCount? rq = item?.planCounts?.firstWhereOrNull((element) => element.playType == 1002);
    return Column(
      children: [
        if(spf != null)
        Row(
          children: [
            _countLabel("胜负", spf.line),
            Container(width: 8),
            ...spf.changeCnt?.values.map<Widget>(
              (e) => Expanded(child: _countItem(e,item?.planTotal))
            ).toList().insertEvery(Container(width: 2)) ?? []
          ],
        ).paddingOnly(bottom: rq!= null?8:12),
        if(rq != null)
        Row(
          children: [
            _countLabel("让球", rq.line),
            Container(width: 8),
            ...rq.changeCnt?.values.map<Widget>(
              (e) => Expanded(child: _countItem(e,item?.planTotal))
            ).toList().insertEvery(Container(width: 2)) ?? []
          ],
        ).paddingOnly(bottom: 12)
      ],
    );
  }
  
  static Widget _countLabel(String? type, String? line){
    return SizedBox(
      width: 40,
      child: Block(
        cardStyle: const CardStyle(
          color: Colours.greyF2F3F7,
          radius: 4,
          height: 40,
          shadow: BoxShadow(color: Colors.transparent)
        ),
        child: DefaultTextStyle(
          style: const TextStyle(fontSize: 11,color: Colours.text),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(height: 5),
              QkdText(type ?? "").center,
              QkdText(line.hasValue?line!:"0").center,
              Container(height: 5)
            ],
          ),
        )
      ),
    );
  }

  static Widget _countItem(CountType? count,int? planTotal){
    return DefaultTextStyle(
      style: TextStyle(fontSize: 11,color: count?.total.hasValue == true?Colours.text:Colours.greyCC),
      child: Block(
        cardStyle: const CardStyle(
          color: Colours.greyF2F3F7,
          radius: 4,
          height: 40,
          shadow: BoxShadow(color: Colors.transparent)
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            QkdText(count?.typeName ?? "").paddingOnly(top: 4).center,
            QkdText("${count?.total ?? 0}",
              color: count?.color
            ).center,
            LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) =>
                Container(
                  decoration: BoxDecoration(
                    color: count?.color,
                    borderRadius: BorderRadius.circular(5.5)
                  ),
                  height: 4,width: constraints.maxWidth*(count?.total?.toDouble() ?? 0)/(planTotal ?? 1),
                ),
            )
          ],
        ),
      ),
    );
  }
}
